package routers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"io/ioutil"
	"object/go_cms/controllers/admin"
	"object/go_cms/models"
)

func initAdmin() {
	//过滤拦截是否登录,有输出时，就会不再继续执行，所以在函数内发生任何输出时都会拦截
	beego.InsertFilter("admin/*", beego.BeforeRouter, checkLogin)
	//权限验证
	beego.InsertFilter("admin/*", beego.BeforeRouter, checkAuth)

	//注册注解路由
	//登录
	beego.Include(&admin.LoginAdminController{})
	//主页
	beego.Include(&admin.IndexAdminController{})
	//菜单
	beego.Include(&admin.MenuAdminController{})
	//管理员
	beego.Include(&admin.AdminAdminController{})
	//获取权限
	beego.Include(&admin.AuthAdminController{})
	//用户组
	beego.Include(&admin.GroupAdminController{})
	//配置信息
	beego.Include(&admin.ConfigAdminController{})
	//文章分类
	beego.Include(&admin.ArticleTypeController{})
	//文章
	beego.Include(&admin.ArticleController{})
	//留言管理
	beego.Include(&admin.MessageAdminController{})
	//友情链接
	beego.Include(&admin.LinkAdminController{})
	//文件管理
	beego.Include(&admin.UploadFileAdminController{})
	//文件分类
	beego.Include(&admin.UploadFileTypeAdminController{})

}

//登录拦截器
func checkLogin(ctx *context.Context) {
	_, ok := ctx.Input.Session("aid").(int64)
	urlMap := make(map[string]bool)
	//设置不用拦截的路由
	urlMap["/admin/login"] = true
	urlMap["/admin/login_sub"] = true

	uri := ctx.Request.RequestURI
	if !ok && !urlMap[uri] {
		ctx.Redirect(302, "/admin/login")
	}
}

//权限拦截器
func checkAuth(ctx *context.Context) {
	aid, _ := ctx.Input.Session("aid").(int64)
	urlMap := make(map[string]bool)
	uri := ctx.Request.URL.Path
	if aid != 1 {
		auth := models.AuthModels{}
		urlMap[uri] = auth.IsAuth(aid, uri)
	}
	//设置不用拦截的路由
	urlMap["/admin/login"] = true
	urlMap["/admin/login_sub"] = true
	urlMap["/admin/login_out"] = true
	urlMap["/admin/index"] = true
	urlMap["/admin/welcome"] = true
	urlMap["/admin/auth/getauth"] = true

	//1不用过滤
	if aid != 1 {
		if !urlMap[uri] {
			if ctx.Input.IsAjax() {
				res := make(map[string]interface{})
				res["Code"] = 1
				res["Msg"] = "没有访问权限"
				_ = ctx.Output.JSON(res, false, false)
			} else {
				ctx.Output.ContentType("text/html; charset=utf-8")
				tpl, _ := ioutil.ReadFile("./views/err/403.html")
				_, _ = ctx.ResponseWriter.Write(tpl)
			}
		}
	}
}
